package com.heiwa.email163;


import javax.mail.*;
import javax.mail.internet.MimeMessage;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Properties;

public class QQMailReader {
    public static void main(String[] args) throws Exception {
        String host = "imap.qq.com"; // QQ企业邮箱的IMAP服务器地址
        String username = "1241835017@qq.com";
        String password = "uaafohxuvdjwhhjf";

        Properties properties = new Properties();
        properties.put("mail.host", host);
        properties.put("mail.port", "143");
        properties.put("mail.store.protocol", "imap");
        properties.put("mail.imap.ssl.enable", "true");

        Session emailSession = Session.getDefaultInstance(properties);
        Store store = emailSession.getStore("imap");
        System.out.println("Connecting to email server");
        store.connect(host, username, password);
        System.out.println("Connected to email server");
        Folder emailFolder = store.getFolder("Sent"); // 已发送邮件通常在Sent文件夹中
        emailFolder.open(Folder.READ_ONLY);
        Message[] messages = emailFolder.getMessages();
        // 让messages 数组按日期排序
        Arrays.sort(messages, Comparator.comparing(message -> {
            try {
                return message.getSentDate();
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        }));
        for (Message message : messages) {
            MimeMessage mimeMessage = (MimeMessage) message;
            System.out.println("From: " + mimeMessage.getFrom()[0]);
            System.out.println("Subject: " + mimeMessage.getSubject());
            Flags flags = mimeMessage.getFlags();
            System.out.println("Is Answered: " + flags.contains(Flags.Flag.ANSWERED));
            System.out.println("Is Seen: " + flags.contains(Flags.Flag.SEEN));
            // 可以添加更多需要的信息
        }

        emailFolder.close(false);
        store.close();
    }
}